<template>
  <div class="wrap">
    <el-row>
      <el-col :span="24" class="warp-main">
        <!--工具条-->
        <el-col :span="24"  class="header-wrap">
          <el-form :inline="true" :model="filters" label-width="100px" size="medium">
            <el-form-item label="标题名称：">
              <el-input v-model="filters.title" placeholder="请输入关键字搜索"></el-input>
            </el-form-item>
            <el-form-item label="启用状态：">
              <el-select v-model="filters.status" placeholder="请选择" @change="getSearchStatus">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchRoles">搜索</el-button>
              <el-button type="primary" @click="showAddDialog">新增</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!--列表-->
        <el-table :data="getAllRoles" :border="true" style="width: 100%;">
          <el-table-column type="expand" >
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="公告内容:" >
                  <span >{{props.row.content}}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column type="index" align="center" ></el-table-column>
          <el-table-column prop="title" label="标题名称" align="center"></el-table-column>
          <el-table-column label="启用状态" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.status == 0">有效</el-tag>
              <el-tag type="danger" v-if="scope.row.status == 1">无效</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="showEditDialog(scope.$index,scope.row)">编辑</el-button>
              <el-button type="danger" @click="deleteRole(scope.$index,scope.row)" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="float:right;margin-top:15px;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
          </el-pagination>
        </div>

        <!--新增界面-->
        <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" width="70%" @close="addClose('addForm')" fullscreen>
          <el-form :model="addForm" label-width="100px" :rules="rule" ref="addForm">
            <!-- 输入框-->
            <el-form-item label="标题:" prop="title">
              <el-input v-model="addForm.title" auto-complete="off"></el-input>
            </el-form-item>
            <!--<el-form-item label="发布内容:" prop="content">
              <el-input  v-model="addForm.content" type="textarea" :rows="6" placeholder="请输入内容"></el-input>
            </el-form-item>-->
            <div class="ueditor">
              <UE :config="configAdd" ref="ueAdd"></UE>
            </div>
            <el-form-item label="启用状态:" prop="status">
              <el-radio v-model="addForm.status" label="0">有效</el-radio>
              <el-radio v-model="addForm.status" label="1">无效</el-radio>
            </el-form-item>
            <el-form-item label="上传公告图片:">
              <el-upload class="upload-demo" action="/api/manager/v1/file/upload"
                         name="file"
                         :data="fileType1"
                         :on-success="onSuccess"
                         :before-upload="beforeUploadAdd"
                         :on-error="onError"
                         multiple
                         :limit="1"
                         list-type="picture-card"
                         :on-exceed="handleExceed"
                         :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="图片成功地址:" prop="imgUrl" v-show="false">
              <el-input  v-model="addForm.imgUrl" auto-complete="off" placeholder="请输入url地址"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click.native="addFormVisible = false">取消</el-button>
            <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
          </div>
        </el-dialog>

        <!-- 编辑 -->
        <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" width="70%" @close="edaitClose" fullscreen>
          <el-form :model="editForm" label-width="100px" :rules="rule" ref="editForm">
            <!-- 输入框-->
            <el-form-item label="标题:" prop="title">
              <el-input v-model="editForm.title" auto-complete="off"></el-input>
            </el-form-item>
            <!--<el-form-item label="发布内容:" prop="ue">
              <el-input  v-model="editForm.content" type="textarea" :rows="6" placeholder="请输入内容"></el-input>
            </el-form-item>-->
            <div class="ueditor" v-if="isShow">
              <UE :config="configEditor" :id="ue1" ref="ue" :defaultMsg="val"></UE>
            </div>
            <el-form-item label="启用状态:">
              <el-radio-group v-model="editForm.status">
                <el-radio class="radio" :label="0">有效</el-radio>
                <el-radio class="radio" :label="1">无效</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="上传公告图片:">
              <el-upload class="upload-demo"
                         ref="upload"
                         action="/api/manager/v1/file/upload"
                         :data="fileType2"
                         :before-upload="beforeUploadEdit"
                         :on-success="onSuccessUpdate"
                         :on-error="onErrorUpdate"
                         :file-list="fileList2"
                         :show-file-list="flag"
                         :limit="1"
                         :on-exceed="handleExceed"
                         list-type="picture-card"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="图片预览:" prop="imgUrl">
              <el-card :body-style="{ padding: '0px' }">
                <img :src="editForm.imgUrl" class="image">
              </el-card>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="getContent">add</el-button>
            <el-button @click.native="editFormVisible = false">取消</el-button>
            <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
          </div>
        </el-dialog>

      </el-col>
    </el-row>
  </div>
</template>
<script type="text/ecmascript-6">
  import UE from '@/components/common/UE';
  import configEditor from '../../../../static/ueditor/configEditor';
  import configAdd from '../../../../static/ueditor/configEditor';
  import {fetch, post} from '@/utils/http'
  let Base64 = require('js-base64').Base64;
  export default{
    data(){
      let validateTitle = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入标题'));
        } else {
          callback();
        }
      };
      let validateContent = (rule, value, callback) => {
        if (value === '') {
          callback();
        } else {
          callback();
        }
      };
      return {
        val: '',
        isShow: false,
        flag: true,
        checkId:1,
        getMenuData:[],
        selectDta:[],
        options: [{
          value: '',
          label: '全部'
        }, {
          value: '0',
          label: '有效'
        }, {
          value: '1',
          label: '无效'
        }],
        filters: {
          title:'',
          status:''
        },
        fileList: [],
        fileType1:{
          "fileType" : "SUMMARY_EVENT"
        },
        fileList2: [],
        fileType2:{
          "fileType" : "SUMMARY_EVENT"
        },

        currentPage: 1,
        totalCount: 0,
        size: 10,
        getAllRoles: [],
        //编辑相关数据
        editFormVisible: false,//编辑界面是否显示
        editLoading: false,

        editForm: {
          title: '',
          content: '',
          status: '',
          url: ''
        },

        //新增相关数据
        addFormVisible: false,//新增界面是否显示
        addLoading: false,
        rule: {
          title: [
            { validator: validateTitle, trigger: 'blur' }
          ],
          content: [
            { validator: validateContent, trigger: 'blur' }
          ]
        },
        addForm: {
          title: '',
          content: '',
          status: '0',
          imgUrl: '',
          imgName: ''
        },
        // ueditor新增时候初始配置
        configAdd: configAdd,
        // ueditor编辑时候初始配置
        configEditor : configEditor,
        ue1: ''
      }
    },
    methods: {
      // 获取富文本框内容
      getContent(){
        return this.$refs.ue.getUEContent();
      },
      addContent() {
        return this.$refs.ueAdd.getUEContent();
      },
      beforeUploadAdd(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
        }
        return isJPG || isPNG;
      },
      onSuccess(response, file, fileList) {
        this.addForm.imgUrl = file.response.data;
        this.addForm.imgName = file.name;
      },
      onError(response, file, fileList) {
        this.$message({
          showClose: true,
          message: '图片上传失败！',
          type: 'error'
        });
      },

      handleExceed(files, fileList) {
        this.$message.warning(`当前超出限制！本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeUploadEdit(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
        }
        return isJPG || isPNG;
      },
      onSuccessUpdate(response, file, fileList) {
        this.editForm.imgUrl = file.response.data;
      },
      onErrorUpdate(response, file, fileList){
        this.$message({
          showClose: true,
          message: '图片上传失败！',
          type: 'error'
        });
      },

      handleSizeChange(val) {
        this.size = val;
        this.getRoles();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getRoles();
      },

      //显示编辑界面
      showEditDialog: function (index, row) {
        this.isShow = true;
        this.editFormVisible = true;
        this.ue1 = String(row.id)
        this.editForm = Object.assign({}, row);
        this.val = this.editForm.content
      },
      edaitClose() {
        this.fileList2 = [];
        setTimeout(() => {
          this.isShow = false;
        },500)
      },
      //编辑
      editSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              this.fileList2 = [];
              let para = Object.assign({}, this.editForm);
              para.content = Base64.encode(this.getContent())
              post('/api/manager/v1/consultation/updateConsultation',para).then((res) => {
                this.editLoading = false;
                this.$refs.ue.clearContent()
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                setTimeout(() => {
                  this.isShow = false;
                },500)
                this.getRoles();
              });
            });
          }
        });
      },

      //新增--跳转
      showAddDialog: function () {
        this.addFormVisible = true;
      },
      addClose(addForm) {
        this.$refs[addForm].resetFields();
        this.fileList = [];
        this.$refs.ueAdd.clearContent();
      },
      //新增提交
      addSubmit: function () {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              let _this = this;
              this.addLoading = true;
              let para = Object.assign({}, this.addForm);
              para.content = Base64.encode(this.addContent());
              post('/api/manager/v1/consultation/addConsultation',para).then((response) => {
                this.addForm.title = '';
                this.fileList = [];
                this.addLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.addFormVisible = false;
                this.getRoles();
              });
            });
          }
        });
      },
      getSearchStatus(value) {
        this.getRoles();
      },
      //获取用户列表
      getRoles() {
        let para = {
          pageIndex: this.currentPage,
          pageSize: this.size
        };
        post('/api/manager/v1/consultation/queryConsultation',para).then((response) => {
          response.data.data.map((val) => {
            val.content = Base64.decode(val.content)
          })
          this.getAllRoles = response.data.data;
          this.totalCount = response.data.totalCount
          this.size = response.data.pageSize
        });
      },
      //搜索
      searchRoles() {
        let para = {
          pageIndex: this.currentPage,
          pageSize: this.size
        };
        if(!this.filters.title.replace(/\s/g, "") == '') {
          para.title = this.filters.title.replace(/\s/g, "")
        }
        if(!this.filters.status == '') {
          para.status = this.filters.status
        }
        post('/api/manager/v1/consultation/queryConsultation',para).then((response) => {
          this.getAllRoles = response.data.data;
          this.totalCount = response.data.totalCount;
          this.size = response.data.pageSize
        })
      },
      //删除
      deleteRole: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'}).then(() => {
          let para = {id: row.id};
          post('/api/manager/v1/consultation/deleteConsultation',para).then((response) => {
            if(response.data.success == 2){
              this.$message({
                message: response.data.msg,
                type: 'error'
              });
            }else{
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }
            this.getRoles();
          })
        }).catch(() => {
          // 超时
        });
      },
    },
    components: {
      UE
    },
    mounted() {
      this.$nextTick(() => {
        this.getRoles();
      })
    }
  }
</script>

<style lang="scss" scoped>
  .wrap {
    /*padding: 20px;*/
    .ueditor {
      margin-left: 120px;
    }
  }
  .header-wrap{
    margin-bottom: 60px;
    background-color: #66BFBF;
    border-radius: 6px;
  }
  .el-form-item {
    margin-top: 22px;
    margin-left: 22px;
  }
  .demo-table-expand label {
    font-weight: bold;
  }
  .el-form-item label{
    padding-right: 200px;
  }
</style>
